package servlet;

import bean.User;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/getuser")
public class getUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接受参数
        String uid = req.getParameter("uid");
        int userId = Integer.parseInt(uid);
        User user = null;
        switch (userId){
            case  1:
                user = new User(1,123,123456); // 此时 是java类型的数据
                break;
            case  2:
                user = new User(2,234,123456); // 此时 是java类型的数据
                break;
            case  3:
                user = new User(3,345,123456); // 此时 是java类型的数据
                break;
            case  4:
                user = new User(4,456,123456); // 此时 是java类型的数据
                break;
            default:
                user = new User();
        }
        // 数据转换，把java格式转化为json格式
        JSONObject jsonObject = JSONObject.fromObject(user);

        //乱码处理
        //req.setCharacterEncoding("text/html;charset=UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.print(jsonObject);

    }
}
